package com.wellview.template.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.alipay.sdk.auth.AlipaySDK;
import com.mob.MobApplication;
import com.wellview.template.BaseActivity;
import com.wellview.template.R;
import com.wellview.template.logger.Logger;
import com.wellview.template.modle.BehaviorFactory;
import com.wellview.template.modle.LoginBehavior;
import com.wellview.template.utils.NetTools;
import com.wellview.template.utils.PatternUtils;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by jizi.chen on 2017/8/28.
 */

public class LoginActivity extends BaseActivity implements PlatformActionListener {

    @BindView(R.id.tv_page_name)
    TextView tvPageName;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.btn_code)
    Button btnCode;
    @BindView(R.id.tv_agreement)
    TextView tvAgreement;
    @BindView(R.id.btn_login)
    Button btnLogin;

    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private static final int MSG_AUTH_COMPLETE = 4;


    @Override
    protected void beforeShow(Bundle savedInstanceState) {

    }

    @Override
    public void bindView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    public void findAllViews() {
        tvPageName.setText("登录");
    }

    @Override
    public void setAllListeners() {

    }

    @Override
    public void doProcess() {

    }

    @OnClick({R.id.btn_code, R.id.tv_agreement, R.id.btn_login,R.id.ib_wechat,R.id.ib_sina,R.id.ib_qq, R.id.ib_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_code:
                requestCode();
                break;
            case R.id.tv_agreement:

                break;
            case R.id.btn_login:
                requestLogin();

                break;
            case R.id.ib_wechat:
                Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                authorize(wechat);
                break;
            case R.id.ib_sina:
                Platform sina = ShareSDK.getPlatform(SinaWeibo.NAME);
                authorize(sina);
                break;
            case R.id.ib_qq:
                Platform qq = ShareSDK.getPlatform(QQ.NAME);
                authorize(qq);
                break;
            case R.id.ib_alipay:
                break;

        }
    }

    private void authorize(Platform platform) {
        if (platform == null){
            Logger.i(TAG,"platform is null"+platform.toString());
            return;
        }
//        platform.removeAccount(true);
        platform.setPlatformActionListener(this);
        //关闭SSO授权
        platform.SSOSetting(true);
        platform.showUser(null);
    }

    private void requestCode() {
        if (isCounting){
            Toast.makeText(this, "请稍后再试", Toast.LENGTH_SHORT).show();
            return;
        }
        String phone = etPhone.getText().toString();
        if (!PatternUtils.checkCellphone(phone) && !PatternUtils.checkTelephone(phone)){
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        startProgressDialog();
        boolean networkConnected = NetTools.isNetworkConnected(this);
        Logger.i(TAG, "networkConnected >> " + networkConnected);
//        if (networkConnected){
//            LoginBehavior loginBehavior = (LoginBehavior) BehaviorFactory.create(LoginBehavior.class);
//            HashMap<String,String> pMap = new HashMap<>();
//            pMap.put("mobile",phone);
//            loginBehavior
//                    .addParam(pMap)
//                    .url(Constant.URL_HOST + Constant.SEND_MSG)
//                    .build(CodeBean.class)
//                    .onResult(new BaseBehavior.ResponseListener<CodeBean>() {
//                        @Override
//                        public void onSuccess(Call call, CodeBean response) {
//                            Log.i(TAG,"Thread "+Thread.currentThread().getName());
//                            Logger.i(TAG,"CodeBean "+response.toString());
//                            stopProgressDialog();
//                            if (response.getCode() == 1){
//                                CodeBean.DataBean data = response.getData();
//                                if (data == null){
//                                    Logger.e(TAG,"message no send");
//                                    showToast(response.getMessage());
//                                }else {
//                                    Logger.e(TAG,"message has send");
//                                    startTimerCount();
//                                }
//                            }
//                        }
//                        @Override
//                        public void onFailure(Call call, Exception e) {
//                            showToast("网络错误");
//                            stopProgressDialog();
//                        }
//                    });
//        }else {
//            showToast("网络未连接");
//            stopProgressDialog();
//        }
    }

    private int count = 60;
    private boolean isCounting = false;
    private synchronized void startTimerCount() {
        isCounting = true;
        final Timer timer = new Timer(true);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnCode.setText((count--) + "秒");
                        if (count == 0) {
                            count = 60;
                            btnCode.setText("点击获取");
                            isCounting = false;
                            timer.cancel();
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    private void requestLogin() {
        String phone = etPhone.getText().toString();
        if (!PatternUtils.checkCellphone(phone) && !PatternUtils.checkTelephone(phone)){
            showToast("请输入正确的手机号");
            return;
        }
        String code = et_code.getText().toString();
        if (TextUtils.isEmpty(code)){
            showToast("请输入验证码");
            return;
        }
        startProgressDialog();
        boolean networkConnected = NetTools.isNetworkConnected(this);
        Logger.i(TAG, "networkConnected >> " + networkConnected);
        if (networkConnected){
            LoginBehavior loginBehavior = (LoginBehavior) BehaviorFactory.create(LoginBehavior.class);
            HashMap<String,String> pMap = new HashMap<>();
            pMap.put("username",phone);
            pMap.put("areaid",code);
            pMap.put("code",code);
//            loginBehavior
//                    .addParam(pMap)
//                    .url(Constant.URL_HOST + Constant.USER_LOGIN)
//                    .method(BaseBehavior.METHODD_PULL)
//                    .build(LoginBean.class)
//                    .onResult(new BaseBehavior.ResponseListener<LoginBean>() {
//                        @Override
//                        public void onSuccess(Call call, LoginBean response) {
//                            Log.i(TAG,"Thread "+Thread.currentThread().getName());
//                            writeLoginMessage(response);
//                            stopProgressDialog();
//                        }
//                        @Override
//                        public void onFailure(Call call, Exception e) {
//                            Log.i(TAG, "requestLogin " + e.getMessage());
//                            stopProgressDialog();
//                            showToast("网络错误");
//                            removeLoginMessage();
//                        }
//                    });
        }else {
            Toast.makeText(this, "网络未连接", Toast.LENGTH_SHORT).show();
        }
    }

    private void goMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Logger.i(TAG,"platform:"+platform.toString()+"action: "+action);
        Logger.i(TAG,"platform.getDb().getUserId():"+platform.getDb().getUserId());
        Logger.i(TAG,"platform.getDb().getUserId():"+platform.getDb().getUserIcon());
        Logger.i(TAG,"platform.getDb().getUserId():"+platform.getDb().getUserGender());
        Logger.i(TAG,"platform.getDb().getUserId():"+platform.getDb().getUserName());
        if (action == Platform.ACTION_USER_INFOR) {
            Message msg = new Message();
            msg.what = MSG_AUTH_COMPLETE;
            msg.obj = new Object[] {platform.getName(), res};
            handler.sendMessage(msg);
        }
    }

    public void onError(Platform platform, int action, Throwable t) {
        Logger.i(TAG,"platform:"+platform.toString()+"action: "+action);
        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        t.printStackTrace();
    }

    public void onCancel(Platform platform, int action) {
        Logger.i(TAG,"platform:"+platform.toString()+"action: "+action);
        if (action == Platform.ACTION_USER_INFOR) {
            handler.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }

    @Override
    protected void handleChildMsg(Message msg) {
        switch (msg.what) {
            case MSG_AUTH_CANCEL: {
                //取消授权
                showToast(R.string.auth_cancel);
            }
            break;
            case MSG_AUTH_ERROR: {
                //授权失败
                showToast(R.string.auth_error);
            }
            break;
            case MSG_AUTH_COMPLETE: {
                //授权成功
                showToast(R.string.auth_complete);
                Object[] objs = (Object[]) msg.obj;
                String platform = (String) objs[0];
                HashMap<String, Object> res = (HashMap<String, Object>) objs[1];
                Logger.i(TAG,platform+"res: "+res.toString());
//                if (signupListener != null && signupListener.onSignin(platform, res)) {
//                    SignupPage signupPage = new SignupPage();
//                    signupPage.setOnLoginListener(signupListener);
//                    signupPage.setPlatform(platform);
//                    signupPage.show(activity, null);
//                }
            }
            break;

        }
    }

    //    private void writeLoginMessage(LoginBean response) {
//        LoginBean.DataBean.UserBean user = null;
//        try {
//            user = response.getData().getUser();
//        } catch (Exception e) {
//            Log.i(TAG, "login response error");
//            showToast("登录失败");
//            e.printStackTrace();
//        }
//        if (user == null) {
//            Log.i(TAG, "login response null");
//            showToast("登录失败");
//            return;
//        }
//        SharePrefrenceUtil.put(LoginActivity.this, "login", "true");
//        SharePrefrenceUtil.put(LoginActivity.this, "last_login_time", "" + System.currentTimeMillis());
//        SharePrefrenceUtil.put(LoginActivity.this, "account", "" + user.getAccount());
//        SharePrefrenceUtil.put(LoginActivity.this, "userid", "" + user.getUserid());
//        SharePrefrenceUtil.put(LoginActivity.this, "nickname", "" + user.getNickname());
//        SharePrefrenceUtil.put(LoginActivity.this, "phone", "" + user.getAccount());
//        goMainActivity();
//    }

}
